//
//  YHKRefreshView.swift
//  xinlangweiBo2
//
//  Created by 杨和逵 on 16/3/4.
//  Copyright © 2016年 yanghekui. All rights reserved.
//

import UIKit


/**
 1.分析界面
 2.分析功能
 
 
 */

//分析出三个状态
enum RefreshType: Int{
    //正常状态
    case Normal = 0
    
    //拖拽的状态
    case Pulling = 1
    
    //加载状态
    case Loading = 2
}



class YHKRefreshView: UIControl {
    
    //成员变量
    var scrollView:UIScrollView?
    
    //记录一下过去的状态
    var oldStatus:RefreshType = .Normal
    
    //定义一个属性，来记录状态，默认是 正常状态
    var status:RefreshType = .Normal{
        
        didSet{
            
            switch status{
                
            case .Normal:print("正常状态")
                
                messageLabel.text = "下拉刷新"
                
            case .Pulling: print("下拉状态")
                
                messageLabel.text = "释放刷新"
                
            case .Loading: print("加载中...")
                
                messageLabel.text = "加载中...."
                
                //加载的时候，让视图显示在Nav下边 修改scrollView?.contentInset
                var inset = scrollView?.contentInset
                
                inset?.top += 64//下滑64
                
                scrollView?.contentInset = inset!
                
                //没有触发 ValueChanged的事件
             sendActionsForControlEvents(UIControlEvents.ValueChanged)
                
                //记录加载的状态
                oldStatus = .Loading
                
                //加载完之后，记得恢复它的高度
            }
            
        }
    }
    
    
    //实现加载完成数据之后调用的方法
    func endRefreshing(){
        
        //改变状态
        status = .Normal
        
        if oldStatus == .Loading{
            
            //修改高度
            var inset = scrollView?.contentInset
            
            inset?.top -= 64
            
            scrollView?.contentInset = inset!
            
            //数据加载完成之后，还需要恢复下标记为Normal
            oldStatus = .Normal
            
        }
    }
    
    
    
    ///添加KVO
    //这个方法是，我们把子控件添加到父控件的时候调用的这个方法
    //newSuperview 是UITableView的 父控件
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        super.willMoveToSuperview(newSuperview)
        
        //1.先把newSuperview 转换为 UIScrollView
         scrollView = newSuperview as? UIScrollView
        
        //2.添加监听
        scrollView?.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
        
    }
    
    //上面KVO实现了，监听，它监听的属性就是偏移量，
    //所以这个方法给 ------> 可以获取的偏移量,
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
//        print(scrollView?.contentOffset)
        
        //判断他在拖拽的时候的偏移量
        if scrollView!.dragging{//拖拽的时候
        
        if scrollView?.contentOffset.y < -150 {
            
//            print("改变成 释放刷新")
            //记录下当前的状态
            status = .Pulling
            
        }else if scrollView?.contentOffset.y < -114 && scrollView?.contentOffset.y > -150{
            
            print("正常状态，下拉刷新")
            //记录下当前的状态
            status = .Normal
            }
            
        }else{ //松手的时候
           
            if scrollView?.contentOffset.y < -150 && status == .Pulling {
//                print("加载中。。。")
                //记录下当前的状态
                status = .Loading
            }
        }
        
        
        
        
    }
    
    
    
    
    
    

    //第一部：
   override init(frame: CGRect) {
        super.init(frame: frame)
    
         backgroundColor = UIColor.yellowColor()
         setUpView()
    
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
 
    //第二部：
    private func  setUpView(){
        
        //设置frame
        var frame = self.frame
        frame.size = CGSizeMake(kUIScreenWidth, 50)
        frame.origin.y = -50
        //赋值
        self.frame = frame
        
        
    
    //添加控件
        addSubview(messageLabel)
        addSubview(arrowImageView)
        addSubview(loadingImageView)
        
        
    //设置约束
       ///居中，然后向右走一点
        messageLabel.snp_makeConstraints { (make) -> Void in
            
            make.centerX.equalTo(self.snp_centerX).offset(20)
                make.centerY.equalTo(self.snp_centerY)
            
        }
    
        ///居中，然后想左走一点
        arrowImageView.snp_makeConstraints { (make) -> Void in
            
             make.right.equalTo(messageLabel.snp_left)
            make.centerY.equalTo(self.snp_centerY)
        }
    
        ///
        loadingImageView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowImageView.snp_center)
        }
        
        
    }
    
    ///第三部 懒加载
    
    ///提示语
    private lazy var messageLabel: UILabel = {
        
        let label = UILabel()
        
        label.text = "下拉刷新"
        
        label.textColor = UIColor.redColor()
        
        label.font = UIFont.systemFontOfSize(15)
        

        
      return label
    }()
    
    ///箭头
    private lazy var arrowImageView:UIImageView = {
    
    let arrow = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
        
        return arrow
    
    
    }()
    
    ///加载视图
    private lazy var loadingImageView: UIImageView = {
    
    let loading = UIImageView(image: UIImage(named: "tableview_loading"))
    
        //先让图片隐藏
        loading.hidden = true
        
        return loading
    
    }()

}










